package com.RedRiver.hospitalsystem.record_service.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.RedRiver.hospitalsystem.finance_service.client.BillClient;
import com.RedRiver.hospitalsystem.finance_service.client.param.CreateBillFromClient;
import com.RedRiver.hospitalsystem.finance_service.client.param.FindBillAllInfoClient;
import com.RedRiver.hospitalsystem.patient_service.client.PatientClient;
import com.RedRiver.hospitalsystem.patient_service.client.param.NewPatientForm;
import com.RedRiver.hospitalsystem.personal_service.client.ScheduleClient;
import com.RedRiver.hospitalsystem.personal_service.client.param.RegisterInformationForm;
import com.RedRiver.hospitalsystem.personal_service.client.param.ScheduleDoctorInfo;
import com.RedRiver.hospitalsystem.record_service.common.Record_serviceResultCode;
import com.RedRiver.hospitalsystem.record_service.common.exception.SerialException;
import com.RedRiver.hospitalsystem.record_service.form.CreateSerialForm;
import com.RedRiver.hospitalsystem.record_service.info.GetTimeByIdInfo;
import com.RedRiver.hospitalsystem.record_service.infra.mapper.SerialMapper;
import com.RedRiver.hospitalsystem.record_service.infra.model.Serial;
import com.RedRiver.hospitalsystem.record_service.service.SerialService;
import com.RedRiver.hospitalsystem.result.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 龙世超
 * @since 2022-04-26
 */
@Service
public class SerialServiceImpl extends ServiceImpl<SerialMapper, Serial> implements SerialService {

    @Resource
    private BillClient billClient;

    @Resource
    private PatientClient patientClient;

    @Resource
    private ScheduleClient scheduleClient;

    @Override
    public Result<?> addSerial(CreateSerialForm createSerialForm) {
        RegisterInformationForm form = new RegisterInformationForm();
        form.setDate(createSerialForm.getSerialDate());
        form.setDoctorId(createSerialForm.getDoctorId());
        Result<String> result = scheduleClient.registerInformation(form);
        if (result.getData() != null) {
            //添加患者信息
            NewPatientForm patientForm = BeanUtil.copyProperties(createSerialForm, NewPatientForm.class);
            //获取生日

            patientForm.setPatientCard(createSerialForm.getSerialCard());
            String serialCard = createSerialForm.getSerialCard();
            System.out.println(serialCard.length());
            String s = serialCard.substring(6, 14);
            patientForm.setPatientBirthday(s);

            //获取年纪
            int y = Integer.parseInt(s.substring(0, 4));
            int year = LocalDateTime.now().getYear();
            patientForm.setPatientAge(year - y);

            //获取性别
            int sex = Integer.parseInt(serialCard.substring(16, 17));
            patientForm.setPatientSex(sex % 2 == 0 ? 0 : 1);


            //验证该患者今天是否挂号以及挂号是否使用
            List<Serial> serials = baseMapper.selectList(new QueryWrapper<Serial>().eq("serial_card", createSerialForm.getSerialCard())
                    .eq("papers_id", createSerialForm.getPapersId()).eq("serial_state", 0));
            System.out.println(serials);
            boolean b = false;
            int patientId = 0;
            if (serials.size() != 0) {
                for (Serial serial : serials) {
                    LocalDateTime now = serial.getSerialDate();
//                LocalDateTime time = LocalDateTime.of(now.getYear(), now.getMonth(), now.getDayOfMonth(), 00, 00, 00);
                    LocalDateTime serialDate = createSerialForm.getSerialDate();
                    if (serialDate.isAfter(LocalDateTime.now())) {

                        LocalDateTime time = LocalDateTime.of(serialDate.getYear(), serialDate.getMonth(), serialDate.getDayOfMonth(), 00, 00, 00);
                        if (now.isBefore(time) || now.isAfter(time.plusDays(1))) {
                            b = true;
                        } else {
                            b = false;
                        }
                    } else {
                        throw new SerialException(Record_serviceResultCode.TIME_IS_ERROR);
                    }
                }
            } else {
                b = true;
            }
            if (b) {
                LocalDateTime now1 = LocalDateTime.now();
                Serial serial = BeanUtil.copyProperties(createSerialForm, Serial.class);
                serial.setSerialNumber(now1.getHour() + "" + now1.getMinute() + "" + now1.getSecond());
                int insert = baseMapper.insert(serial);
                Result<FindBillAllInfoClient> bill1 = null;
                if (insert > 0) {
                    Result<Integer> patient = patientClient.createPatient(patientForm);
                    System.out.println(patient);
                    if (patient.getCode() == 200) {
                        patientId = patient.getData();
                    }
                    List<Serial> doctors = baseMapper.selectList(new QueryWrapper<Serial>().eq("doctor_id", createSerialForm.getDoctorId()));
                    CreateBillFromClient bill = new CreateBillFromClient();
                    bill.setCheckId(serial.getSerialId());
                    bill.setPaymentId(3);
                    bill.setPatientId(patientId);
                    bill.setWorkerId(serial.getDoctorId());
                    bill.setBillPrice(BigDecimal.valueOf(20.00));
                    bill1 = billClient.createBill(bill);
                    System.out.println(bill1);

                    LocalDateTime serialDate = createSerialForm.getSerialDate();
                    LocalDateTime time = LocalDateTime.of(serialDate.getYear(), serialDate.getMonth(), serialDate.getDayOfMonth(), 00, 00, 00);
                    int i = 0;
                    for (Serial doctor : doctors) {
                        if (doctor.getSerialDate().isAfter(time) && doctor.getSerialDate().isBefore(time.plusDays(1))) {
                            i += 1;
                        }
                    }
                    return Result.getInstance().setMsg("挂号成功,您的号码是" + serial.getSerialNumber() + ",当天前面有" + (i - 1) + "个人等候" + "账单编号为"+bill1.getData().getBillId()+"患者编号为"+patientId);
                }
                throw new SerialException(Record_serviceResultCode.CREATE_SERIAL_ERROR);
            }
            throw new SerialException(Record_serviceResultCode.SERIAL_NOT_USER_ERROR);
        }
        throw new SerialException(Record_serviceResultCode.DOCTOR_NOT_EXISTS_ERROR);
    }

    public static void main(String[] args) {
        String time = "2022-05-07";
        int y = Integer.parseInt(time.substring(0, 4));
        int m = Integer.parseInt(time.substring(6, 7));
        int d = Integer.parseInt(time.substring(8, 10));
        LocalDateTime of = LocalDateTime.of(y, m, d, 8, 00, 00);
        System.out.println(of);
        System.out.println(of.isAfter(LocalDateTime.now()));
        System.out.println(LocalDateTime.now());

    }


    @Override
    public Result<?> getNext(Integer doctorId) {
        System.out.println(doctorId);
        LocalDateTime dateTime = LocalDateTime.now();
        System.out.println(dateTime);
        LocalDateTime time1 = LocalDateTime.of(dateTime.getYear(), dateTime.getMonth(), dateTime.getDayOfMonth(), 00, 00, 00);
        List<Serial> serials = baseMapper.selectList(new QueryWrapper<Serial>().eq("doctor_id", doctorId)
                .eq("serial_state", 0).gt("serial_date", time1).lt("serial_date", time1.plusDays(1)));
        System.out.println(serials);
        if (serials.size() != 0) {
            for (Serial serial : serials) {
//                //挂号时间
//                LocalDateTime now = serial.getSerialDate();
//                //挂号当天时间
//                LocalDateTime time = LocalDateTime.of(now.getYear(), now.getMonth(), now.getDayOfMonth(), 00, 00, 00);
//                if (serial.getSerialDate().isAfter(time)) {

                Result<FindBillAllInfoClient> billByCheckId = billClient.findBillByCheckId(serial.getSerialId());
                FindBillAllInfoClient data = billByCheckId.getData();
                if (data != null) {
                    if (data.getBillState() == 1) {
                        return Result.getInstance().setMsg("请" + serial.getSerialNumber() + "号，进行就诊");
                    }
                }
//                }
            }
            throw new SerialException(Record_serviceResultCode.NO_SERIAL_ERROR);
        }
        throw new SerialException(Record_serviceResultCode.NO_SERIAL_ERROR);
    }

    @Override
    public GetTimeByIdInfo getTime(Integer id) {
        Serial serial = baseMapper.selectById(id);
        if (serial != null) {
            GetTimeByIdInfo timeByIdInfo = BeanUtil.copyProperties(serial, GetTimeByIdInfo.class);
            return timeByIdInfo;
        }
        throw new SerialException(Record_serviceResultCode.NO_SERIAL_BYID_ERROR);
    }
}
